import jwt from 'jsonwebtoken'
import { User } from '../models/User'

export const verifyToken = async (token: string) => {
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as { userId: string }
    const user = await User.findById(decoded.userId)
    if (!user) {
      throw new Error('User not found')
    }
    return {
      id: user._id,
      username: user.username,
      role: user.role,
    }
  } catch (err) {
    throw new Error('Invalid token')
  }
}
